package com.huanbao.auth.user.service;

import com.huanbao.auth.feign.CloudNongwuApi;
import com.huanbao.auth.feign.CloudSassApi;
import com.huanbao.auth.user.domain.AuthUser;
import com.huanbao.common.pojo.nwrabc.SysPermission;
import com.huanbao.common.pojo.nwrabc.vo.NwUserDetails;
import com.huanbao.common.pojo.sassrabc.vo.SassUserDetail;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/* ━━━━━━佛祖保佑━━━━━━
 *                  ,;,,;
 *                ,;;'(    社
 *      __      ,;;' ' \   会
 *   /'  '\'~~'~' \ /'\.)  主
 * ,;(      )    /  |.     义
 *,;' \    /-.,,(   ) \    码
 *     ) /       ) / )|    农
 *     ||        ||  \)
 *     (_\       (_\
 * ━━━━━━永无BUG━━━━━━
 * @author ：zjq
 * @date ：2021/3/22 11:15
 * @description: TODO       认证服务器加载用户的类 调接口时候会先回调 这个类,这里去cloud-nongwu获取用户认证信息
 * @version: V1.0
 * @slogan: 天下风云出我辈，一入代码岁月催
 */
@Slf4j
@Service
public class UserService implements UserDetailsService {


    @Autowired
    private CloudNongwuApi cloudNongwuApi;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private CloudSassApi cloudSassApi;


    public HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public HttpServletResponse getResponse() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 如果前端除了 用户名 和 密码 这两个字段，比如 一些验证码 等其他字段 ，可以再  request 中获取到
        String sysFlag = getRequest().getParameter("sysFlag");

        if (StringUtils.isEmpty(username)) {
            log.warn("用户登陆用户名为空:{}", username);
            throw new UsernameNotFoundException("用户名不能为空");
        }

        AuthUser authUser = getUserByName(username);
        return authUser;

    }


    /**
     * 调用 农污 服务 获取 用户
     *
     * @param loginName
     * @return
     */
    public AuthUser getUserByName(String loginName) {

        NwUserDetails nw = cloudNongwuApi.getUserInfoByName(loginName);
        if (null != nw && nw.getSysUser().getId() != -1) {
            // 权限
            List<SysPermission> permissionList = nw.getSysPermissions();
            List<SimpleGrantedAuthority> authorityList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(permissionList)) {
                for (SysPermission sysPermission : permissionList) {
                    authorityList.add(new SimpleGrantedAuthority(sysPermission.getUrllink()));
                }
            }

            // 调用 农污 服务获得的密码，加密后 和前端 传来的 进行对比  + 权限
            AuthUser authUser = new AuthUser(nw.getSysUser().getLoginname(),
                    passwordEncoder.encode(nw.getSysUser().getLoginpwd()), authorityList);

            authUser.setNwUserDetails(nw);
            return authUser;
        }
        return null;

    }


    /**
     * 生成 oauth_client_details 表 密码 的方法
     *
     * @param args
     */
    public static void main(String[] args) {
        String salt = BCrypt.gensalt();
        String hashpw = BCrypt.hashpw("123456".toString(), salt);
        System.out.println(hashpw);
    }
}
